package com.jz.pay.bo.impl;

import com.jz.commom.api.dto.request.Payment;
import com.jz.pay.bo.PaymentBO;
import com.jz.pay.dao.PaymentDao;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class PaymentBOImpl implements PaymentBO {

    @Resource
    PaymentDao PaymentDAO;

    public int create(Payment payment){
        return PaymentDAO.create(payment);
    }

    private static final int tablesLength = 4;
    private static final char[] tmp = new char[String.valueOf(tablesLength).length()];

    static {
        Arrays.fill(tmp, '0');
        Calendar calendar = Calendar.getInstance();
    }

    public int createNew(Payment payment){
        Date now = new Date();
        String str = String.valueOf(now.getTime());
        if(StringUtils.isEmpty(payment.getRid())){
            payment.setId(now.getTime());
            payment.setRid(String.valueOf(now.hashCode()));
        }
        System.out.println("rid: "+payment.getRid());

        String tableName = "payment_"+ buildTableName(payment.getSerial(),tablesLength);
        payment.setTable(tableName);
        if (StringUtils.isEmpty(tableName)){
            throw new RuntimeException("计算异常");
        }
        payment.setCrtTime(now);
        return PaymentDAO.createNew(tableName,payment);
    }

    @Override
    public List<Payment> query(Payment payment) {
        if (StringUtils.isEmpty(payment.getSerial())){
            throw new RuntimeException("查询条件为空");
        }
        String tableName = "payment_"+ buildTableName(payment.getSerial(),tablesLength);
        return PaymentDAO.query(tableName,payment);
    }

    //    public Payment getPaymentById(Long id);
    public Payment getPaymentById(Long id){
        return PaymentDAO.getPaymentById(id);
    }

    public void test(){
        System.out.println("测试spring流程");
    }

    /**
     * 根据关键字生成表名称，不够前缀补0
     * @param key
     * @param tablesLength
     * @return
     */
    private static String buildTableName(String key,int tablesLength){
        int hashCode = (key.hashCode() ^ tablesLength) % tablesLength;
        String suffix = String.valueOf(hashCode > 0 ? hashCode : -hashCode);
        // 后缀长度
        char[] sour = suffix.toCharArray();
        char[] tarArr;
        int i = 0;
        if ((i = suffix.length() - sour.length) > 0){
            tarArr = new char[tablesLength];
            System.arraycopy(tmp,0,tarArr,0,sour.length);
            System.arraycopy(sour,0,tarArr,i,sour.length);
        }else{
            tarArr = sour;
        }
        return String.valueOf(tarArr);
    }


}
